//
//  ViewController.m
//  下载大文件
//
//  Created by student on 16/3/31.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
{
    NSMutableData *mData;
    int allLength;
    NSFileHandle *fh;
    
    BOOL bDownLoading;
    NSURLConnection *con; //连接对象
    
    unsigned long long curLength; // 当前长度
}
@property (strong, nonatomic) IBOutlet UIView *progressView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    NSLog(@"%s",__func__);
}
- (IBAction)btnPressed:(id)sender
{
    [self downloadBigFile4];
}

- (void)tounchesBegan:(NSSet<UITouch *> *)toucheswithEvent:](UIEvent *)event
{
    [self downloadBigFile3];
}

#pragma mark - 
- (void)downloadBigFile1
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //获取数据
        NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/resources/videos.zip"];
        NSURL *url = [NSURL URLWithString:urlStr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        //保存下来
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];//保存路径
        
        NSLog(@"保存位置:%@",filePath);
        [data writeToFile:filePath atomically:YES];
    });
}


#pragma mark - 
- (void)downloadBigFile2
{
    NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/resources/videos.zip"];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [con start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%s",__func__);
    NSHTTPURLResponse *r = response;
    allLength = [r.allHeaderFields[@"Content-Length"] intValue];
    mData = [NSMutableData data];
    self.progressView.progress = 0.0f;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"%s",__func__);
    [mData appendData:data];
    NSLog(@"%i%%",mData.length*100/allLength);
    
    self.progressView.progress = (float)mData.length/allLength;
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%s",__func__);
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *filePath = [path stringByAppendingPathComponent:connection.currentRequest.URL.lastPathComponent];//保存的路径
    NSLog(@"保存位置:%@",filePath);
    [NSData writeToFile:filePath atomically:YES];
}

#pragma mark - 
- (void)downloadBigFile3
{
    NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/resources/videos.zip"];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [con start];
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"开始接收: %s",__func__);
    NSHTTPURLResponse *r = response;
    allLength = [r.allHeaderFields[@"Content-Length"] intValue];
    mData = [NSMutableData data];
    self.progressView.progress = 0.0f;
    
    //创建文件
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *filePath = [path stringByAppendingPathComponent:connection.currentRequest.URL.lastPathComponent];// 保存的路径
    
    [fm createFileAtPath:filePath contents:nil attributes:nil];
        // 创建文件读写的指针
        fh = [NSFileHandle fileHandleForWritingAtPath:filePath];
    }

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        [fh writeData:data];
        NSLog(@"接收数据:%i%%",fh.offsetInFile*100/allLength);
    
        self.progressView.progress = (float)fh.offsetInFile/allLength;
    }
    
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSLog(@"接收完毕 %s",__func__);
        [fh closeFile];
    }
}

#pragma mark - 断点续传

- (void)downloadBigFile4
{
    if (bDownLoading)
    {
        [con cancel];
    }
    else
    {
        NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/resources/videos.zip"];
        NSURL *url = [NSURL URLWithString:urlStr];
        
        NSString *tmpFilePath = [NSHomeDirectory() stringByAppendingFormat:@"/tmp/%@",url.lastPathComponent];
        
        NSFileManager *fm = [NSFileManager defaultManager];
        if(![fm fileExistsAtPath:tmpFilePath])
        {
            // 1. 文件不存在，新下载
            // 创建文件
            [fm createFileAtPath:tmpFilePath contents:nil attributes:nil];
            // 创建文件读写的指针
            fh = [NSFileHandle fileHandleForWritingAtPath:tmpFilePath];
            //
            curLength = 0;
            
        }
        else
        {
            // 2. 文件存在就续传
            // 打开文件
            fh = [NSFileHandle fileHandleForWritingAtPath:tmpFilePath];
            // 指针移到最后
            curLength = [fh seekToEndOfFile];
        }
        
        // 设置请求头，告诉服务器断点续传的位置
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        // bytes=当前长度值- (指请求从指定长度之后的数据)
        NSString *rangeStr = [NSString stringWithFormat:@"bytes=%lld-",curLength];
        [request setValue:rangeStr forHTTPHeaderField:@"Range"];
        
        con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        [con start];
        bDownLoading = YES;
    }
    
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"开始接收: %s",__func__);
    NSHTTPURLResponse *r = response;
    NSLog(@"当前长度:%lld,待接收长度:%lld",curLength,[r.allHeaderFields[@"Content-Length"] longLongValue]);
    allLength = curLength + [r.allHeaderFields[@"Content-Length"] longLongValue];
    
    self.progressView.progress = (float)curLength/allLength;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [fh writeData:data];
    NSLog(@"接收数据:%i%%",fh.offsetInFile*100/allLength);
    
    self.progressView.progress = (float)fh.offsetInFile/allLength;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"接收完毕 %s",__func__);
    [fh closeFile];
    bDownLoading = NO;
}





































@end
